//
//  COHotListController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/7.
//

import UIKit

class COHotListController: UIViewController {
    
    var chooseType:NSInteger = 0
    var headHeight:CGFloat = 0.0
    lazy var pageNum: Int = 1
    var countryCode = [CountryCodeModel]()            // 旗帜
    var upgradeModel = MarketModel()
    fileprivate var newAndHot = [HotListModel]()      // 数组

    let homeHeadIdentifier:String = "HomeHeadReusableView"
    var homeHeadView = COHotHeadReusableView()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (SCREENWIDTH - PTW(30))/2;
        layout.itemSize = CGSize(width: width, height: PTW(235))
        layout.sectionInset = UIEdgeInsets(top: PTW(10), left: PTW(10), bottom: PTW(10), right: PTW(10))
        layout.minimumInteritemSpacing = PTW(5)
        layout.minimumLineSpacing = PTW(10)
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.backgroundColor = .clear
        view.dataSource = self
        view.delegate = self
        view.bounces = true
        view.alwaysBounceVertical = true
        view.register(UINib(nibName: "DGNListCollectionCell", bundle: Bundle.main), forCellWithReuseIdentifier: "DGNListCollectionCell")
        view.register(COHotHeadReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: homeHeadIdentifier)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.collectionView.headerRefresh {[weak self] in
            self?.pageNum = 1
            self?.fetchData(true)
        }

        self.collectionView.footerRefresh {[weak self] in
            self?.pageNum += 1
            self?.fetchData(false)
        }
        self.collectionView.headerStartRefreshing()
        NotificationCenter.default.addObserver(self, selector: #selector(finishFollow), name: .FollowFinishNoti, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(marketNoti), name: .kMarketingUpNoti, object: nil)
    }
    
    @objc func finishFollow(){
        if (self.chooseType == 2){
            fetchData(true)
        }
    }
    
    func fetchData(_ isRefresh:Bool = false){
        var params = [String:Any]()
        params["pageNum"]  = self.pageNum
        params["pageSize"] = 30
        if let languageRegion = Locale.preferredLanguages.first{
            if self.chooseType != 2{
                params["useLanguage"] = languageRegion
            }
        }
        var target = COBaseApi.streamerHot(param: params)
        if chooseType == 1{
            target = COBaseApi.streamerNew(param: params)
        }else if chooseType == 2{
            target =  COBaseApi.streamerFollowList(param: params)
        }
        COHttpManager.request(target: target, modelType: COHotResponseModel.self) {[weak self] code, object, success in
            let list = object?.pageData
            if isRefresh == true {
                self?.newAndHot = list ?? [HotListModel]()
                self?.collectionView.headerEndRefreshing()
                self?.collectionView.footerEndRefreshing((list?.count == 0) ? true : false)
                if list?.count ?? 0 > 0{
                    CONodataView.dg_hide((self?.collectionView)!)
                }else {
                    CONodataView.dg_show((self?.collectionView)!)
                }
            }else {
                if list?.count ?? 0 > 0 {
                    if let items = self?.newAndHot, let list = list{
                        self?.newAndHot = items + list
                    }
                }
                self?.collectionView.footerEndRefreshing((list?.count == 0) ? true : false)
            }
            self?.collectionView.reloadData()
        } failureBlock: {[weak self] code, msg in
            self?.collectionView.headerEndRefreshing()
            self?.collectionView.footerEndRefreshing()
        }
    }
    
    @objc func marketNoti(noti:Notification){
        let marketObject = noti.object as? String
        if (marketObject?.isEmptyStr == false){
            let model =  JSONDeserializer<MarketModel>.deserializeFrom(json: marketObject!)
            self.upgradeModel = model!
            let alertView = COMarketAlertView(model: model!)
            alertView.show()
            alertView.certainBlock = { model,type in
                if (type == 1){
                    UIApplication.shared.open(URL(string: model.link)!)
                }else{
                    let url = URL(string: "mailto:\(model.email)")
                    UIApplication.shared.open(url!)
                }
            }
            alertView.closeBlock = { [weak self] in
                DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
                    self?.headHeight = PTW(170)
                    self?.collectionView.reloadData()
                })
            }
        }
    }
}

extension COHotListController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return newAndHot.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DGNListCollectionCell", for: indexPath) as! DGNListCollectionCell
        var model = self.newAndHot[indexPath.item]
        model.countryCodeArr = self.countryCode
        cell.model = model
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let profile = COOtherInfoController()
        let model = self.newAndHot[indexPath.item]
        profile.userId = model.id
        self.navigationController?.pushViewController(profile, animated: true)
    }
    
    //设置HeadView的宽高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        return CGSize(width: SCREENWIDTH, height: self.headHeight)
    }

    //返回自定义HeadView
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader{
            homeHeadView = collectionView.dequeueReusableSupplementaryView(ofKind:kind, withReuseIdentifier: homeHeadIdentifier, for: indexPath) as! COHotHeadReusableView
            if (self.headHeight > 0.0){
                if (self.upgradeModel.image.isEmptyStr == false){
                    homeHeadView.headImg.sd_setUrlImage(self.upgradeModel.image, placeholder: KImaged("coco_home_banner"))
                }else{
                    homeHeadView.headImg.image = KImaged("coco_home_banner")
                }
            }
            homeHeadView.addTap { ges in
                if (self.upgradeModel.link.isEmptyStr == false){
                    UIApplication.shared.open(URL(string: self.upgradeModel.link)!)
                }
            }
        }
        return homeHeadView
    }
}
